<template>
  <div id="" class="">
    <div class="distinguishTitle">
      <p class="titleInfo">图片识别</p>
      <p class="titleDesc">快速识别图片中的信息</p>
    </div>
    <div class="distinguishInput">
      <div class="distinguishSelect">
        <el-select v-model="uploadData.code" placeholder="兽类">
          <el-option v-for="item in options"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div style="" class="inputInfo">
        <!--        <el-input placeholder="请输入内容" v-model="input2">-->
        <!--          <template slot="append" class="browse">浏览</template>-->
        <!--        </el-input>-->
        <el-upload class="uploadWrap" ref="upload" :action=identifyUrl :headers="headers" :data="uploadData"
                   :show-file-list="false" :limit="1" :drag="true" :auto-upload="false" :on-change="fileChange"
                   :on-exceed="fileExceed" :on-success="uploadSuccess" :on-error="uploadError"
                   accept="image/png,image/jpg,image/jpeg,image/bmp" :before-upload="beforeAvatarUpload">
          <div style="display: flex">{{fileName}}
            <div class="browse">浏览</div>
          </div>
          <div slot="tip" class="upload-tip">图片文件类型支持PNG、JPG、JPEG、BMP, 图片大小不超过2M</div>
        </el-upload>
      </div>
      <div class="update" @click="upload">
        开始识别
      </div>
    </div>
    <div class="contentWrapper">
      <!--      props: {-->
      <!--        native: Boolean,  // 是否使用本地，设为true则不会启用element-ui自定义的滚动条-->
      <!--        wrapStyle: {},  // 包裹层自定义样式-->
      <!--        wrapClass: {},  // 包裹层自定义样式类-->
      <!--        viewClass: {},  // 可滚动部分自定义样式类-->
      <!--        viewStyle: {},  // 可滚动部分自定义样式-->
      <!--        noresize: Boolean, // 如果 container 尺寸不会发生变化，最好设置它可以优化性能-->
      <!--        tag: {  // 生成的标签类型，默认使用 `div`标签包裹-->
      <!--          type: String,-->
      <!--          default: 'div'-->
      <!--        }-->
      <!--      }-->
      <el-scrollbar style="height: 100%;">
        <div class="scrollWrap" v-infinite-scroll="load" infinite-scroll-delay="500" infinite-scroll-distance="-15">
          <div class="imgItem" v-for="(item,index) in this.pageidentify" :key="index">
            <div class="imgList">
              <el-image
                  :src="item.filePath"
                  :preview-src-list="getSrcList(index)"
              >
              </el-image>
            </div>
            <div class="imgInfo">
              <div class="infoItem">
                <div class="infoTitle">{{item.t1Val}}</div>
                <div class="infoSpeed">
                  <el-progress :stroke-width="10" :percentage="Number(Number(item.t1Prob).toFixed(2))"></el-progress>
                </div>
              </div>
              <div class="infoItem">
                <div class="infoTitle">{{item.t2Val}}</div>
                <div class="infoSpeed">
                  <el-progress :stroke-width="10" :percentage="Number(Number(item.t2Prob).toFixed(2))"></el-progress>
                </div>
              </div>
              <div class="infoItem">
                <div class="infoTitle">{{item.t3Val}}</div>
                <div class="infoSpeed">
                  <el-progress :stroke-width="10" :percentage="Number(Number(item.t3Prob).toFixed(2))"></el-progress>
                </div>
              </div>
            </div>
            <Corner></Corner>
          </div>
          <p v-if="pageLoading" class="loading">加载中...</p>
          <p v-if="noMore" class="loading">没有更多了</p>
        </div>
      </el-scrollbar>

    </div>
    <Loding v-if="isShowLoading" text="正在识别"></Loding>
  </div>
</template>

<script>
import LoginAPI from '../../../api/loginApi'
import Corner from '../../../components/corner'
import Loding from '../../../components/Loding'
import {DistinguishModel} from '../../../api/distinguish/distinguishModelApi'
let distinguishModel = new DistinguishModel()
export default {
  name: 'distinguishView',
  components: {
    Corner, Loding
  },
  computed: {
    noMore () {
      if (this.isScoll) {
        return this.pageIndex >= this.findPageCount
      }
      return false
    }
  },
  data () {
    return {
      isScoll: false,
      // 大图预览的数据
      urls: [],
      locked: true, // 锁
      pageLoading: false,
      findPageCount: 0, // 数据有多少页
      distinguishData: [],
      pageIndex: 1,
      pageSize: 10,
      isShowLoading: false,
      input1: '',
      input2: '',
      input3: '',
      select: '',
      url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
      srcList: [
        'https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg',
        'https://fuss10.elemecdn.com/1/8e/aeffeb4de74e2fde4bd74fc7b4486jpeg.jpeg'
      ],
      // 复制的
      clientHeight: '',
      loading: false,
      fileName: '请从电脑上传图片或把图片拖拽到这里',
      headers: {},
      uploadData: {
        code: '5YW957G7',
        type: 0
      },
      identifyUrl: 'https://ai.forestrycat.com/ai/image/recognition/upload',
      haveFile: false,
      pageidentify: [],
      identifyResult: [
        {
          't1Prob': 51.69,
          't1Val': '紫沙蛇',
          't2Prob': 18.32,
          't2Val': '环纹华游蛇',
          't3Prob': 7.71,
          't3Val': '赤链蛇',
          'filePath': 'http://files1.forestrycat.com/3,010fa241b89a',
        }
      ],
      totalPages: 0,
      options: [{
        value: '54is6KGM',
        label: '动物'
      }, {
        value: '5YW957G7',
        label: '蛇类'
      }, {
        value: '55eF5a6z',
        label: '病害'
      }, {
        value: '55eF6Jmr',
        label: '病虫'
      }, {
        value: '5qSN54mp',
        label: '植物'
      }],
      value: ''
    }
  },
  created () {
    this.getFindPageData()
  },
  mounted () {
    this.clientHeight = `${document.documentElement.clientHeight}` // 获取浏览器可视区域高度
    this.getToken()
  },
  methods: {
    load () {
      this.pageIndex++
      if (this.pageIndex > this.findPageCount) {
        this.pageLoading = false
        this.isScoll = true
      } else {
        this.pageLoading = true
        this.isScoll = false
        if (this.locked) {
          this.locked = false // 锁
          this.getFindPageDataConcat()
        }
      }
    },
    getToken () {
      var params = {
        grant_type: 'password',
        username: '15322082030',
        password: 'a12345678'
      }
      LoginAPI.identifyLogin(params).then((res) => {
        this.headers = {
          'Authorization': 'Bearer ' + res.data.access_token
        }
      })
    },
    upload () {
      if (this.haveFile === true) {
        this.isShowLoading = true
        this.loading = true
      } else {
        this.$message.error('请选择要上传的文件')
      }
      this.$refs.upload.submit()
    },
    fileChange (file, fileList) {
      if (fileList.length > 0) {
        this.haveFile = true
        this.fileName = '已选择图片，点击按钮开始识别'
      } else {
        this.haveFile = false
      }
    },
    fileExceed (file, fileList) {
      this.$message.error('最多只能选一张图片')
    },
    beforeAvatarUpload (file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!请重新选择')
        this.loading = false
        this.$refs.upload.clearFiles()
        this.haveFile = false
      }
      return isLt2M
    },
    async uploadSuccess (res) {
      if (res.code === 200) {
        this.isShowLoading = false
        this.$refs.upload.clearFiles()
        this.haveFile = false
        // 识别成功后请求后台添加数据
        let user = JSON.parse(localStorage.getItem('user'))
        let params = {
          'userId': user.userId,
          't1Prob': res.result.data[0].score.toFixed(2),
          't1Val': res.result.data[0].name,
          't2Prob': res.result.data[1].score.toFixed(2),
          't2Val': res.result.data[1].name,
          't3Prob': res.result.data[2].score.toFixed(2),
          't3Val': res.result.data[2].name,
          'filePath': res.result.imgUrl
        }
        this.addDistinguishData(params)
        this.getFindPageData()
      } else {
        this.$message.error(res.message)
        this.$refs.upload.clearFiles()
        this.haveFile = false
      }
      this.loading = false
    },
    async addDistinguishData (params) {
      let addResult = await distinguishModel.addDistinguish(params)
      if (addResult.status === 200) {
        this.$message({
          message: '识别成功',
          type: 'success'
        })
        this.getFindPageData()
      }
    },
    uploadError (err) {
      this.isShowLoading = false
      this.$message.error('上传失败，请重试')
      this.$refs.upload.clearFiles()
      this.haveFile = false
      this.loading = false
    },
    slicePage (start, end) {
      this.pageidentify = this.identifyResult.slice(start, end)
    },
    async getFindPageData () {
      this.isScoll = false
      let pageResult = await distinguishModel.getFindPage({
        'pageIndex': 1,
        'pageSize': 10
      })
      if (pageResult.status === 200 && pageResult.data.result.rows.length > 0) {
        this.urls = []
        this.pageidentify = []
        this.pageidentify = pageResult.data.result.rows
        this.findPageCount = pageResult.data.result.totalPageCount
        this.pageidentify.forEach(item => {
          this.urls.push(item.filePath)
        })
      }
    },
    async getFindPageDataConcat (data) {
      this.urls = []
      this.identifyResult = []
      this.distinguishData = []
      let pageResult = await distinguishModel.getFindPage({
        'pageIndex': this.pageIndex,
        'pageSize': this.pageSize
      })
      if (pageResult.status === 200 && pageResult.data.result.rows.length > 0) {
        this.distinguishData = pageResult.data.result.rows
        this.pageidentify = this.pageidentify.concat(this.distinguishData)
        this.findPageCount = pageResult.data.result.totalPageCount
        this.pageidentify.forEach(item => {
          this.urls.push(item.filePath)
        })
        this.locked = true
      }
    },
    getSrcList (index) {
      return this.urls.slice(index).concat(this.urls.slice(0, index))
    }
  }
}
</script>

<style lang="less" scoped>
  .distinguishTitle {
    margin-top: 10px;
    text-align: center;
    margin-bottom: 10px;

    .titleInfo {
      font-size: 2.2rem;
      color: #ffffff;
      margin-bottom: 10px;
    }

    .titleDesc {
      font-size: 1.8rem;
      color: rgba(223, 223, 223, 1);
    }
  }

  .distinguishInput {
    position: relative;
    margin: 0 auto 10px;
    width: 45%;
    min-width: 755px;
    display: flex;

    .distinguishSelect {
      width: 110px !important;

      & /deep/ .el-select .el-input__inner {
        height: 42px;
        border-radius: 3px;
        border: none;
        background: rgba(0, 128, 235, 1);
      }
    }

    .inputInfo {
      margin: 0 2%;
      width: calc(100% - 220px - 2%);

      .uploadWrap {
        & /deep/ .el-upload-dragger {
          color: white;
          background: none;
          border-radius: 2px;
          border: 1px solid #00ecf7;
          height: 42px;
          line-height: 42px;
          font-size: 14px;
          text-indent: 15px;
          width: 100%;
        }

        & /deep/ .el-upload {
          width: 100% !important;
        }
      }

      .browse {
        text-indent: 0;
        background: rgba(0, 128, 235, 1);
        position: absolute;
        right: 0;
        width: 100px;
        height: 42px;
        line-height: 42px;
        font-size: 16px;
      }

      & /deep/ .el-input-group {
        border: 1px solid #00ecf7;
      }

      & /deep/ .el-input__inner {
        border: none;
      }

      & /deep/ .el-input-group__append, .el-input-group__prepend {
        background: rgba(0, 128, 235, 1);
        font-size: 1.6rem;
        color: white;
        border: none;
      }
    }

    .update {
      cursor: pointer;
      border-radius: 3px;
      width: 110px;
      height: 42px;
      line-height: 42px;
      text-align: center;
      color: white;
      font-size: 1.6rem;
      background: rgba(0, 128, 235, 1);
    }
  }

  .contentWrapper {
    /*margin-top: 20px;*/
    /*margin-top: 20px;*/
    /*background-color: red;*/
    width: 100%;
    height: calc(100vh - 222px);
    box-sizing: border-box;
    /*background-color: palevioletred;*/
    /*display: flex;*/
    /*flex-direction: row;*/
    /*flex-wrap: wrap;*/
    /*overflow-y: scroll;*/
    /*& /deep/ .el-scrollbar__thumb{*/
    /*  background-color: red!important;*/
    /*}*/
    /*& /deep/ .el-scrollbar__view {*/
    /*  height: 100%;*/
    /*}*/

    .scrollWrap {
      /*overflow-y: auto;*/
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      /*height: 100%;*/
      box-sizing: border-box;
      padding: 10px 5% 1%;
    }

    /*&:hover::-webkit-scrollbar-thumb {*/
    /*  display: block;*/
    /*  background: rgba(13, 126, 246, .5);*/
    /*}*/

    .imgItem {
      border: 1px solid rgba(81, 191, 210, 1);
      display: inline-flex;
      flex-direction: column;
      width: 18%;
      height: calc((100vh - 247px) * 0.5 * 0.9);
      /*height: 45%;*/
      /*margin-left: 1.5%;*/
      margin-bottom: 1.5%;
      margin-right: 2.2%;
      position: relative;
      padding: 1px;
      box-sizing: border-box;

      .imgList {
        display: flex;
        justify-content: center;
        height: 60%;
        width: 100%;

        img {
          height: 100%;
          width: 100%;
          object-fit: fill;
        }
      }

      .imgInfo {
        padding: 5% 1% 5% 5%;
      }

      .infoItem {
        display: flex;
        margin-bottom: 8%;
      }

      .infoTitle {
        width: 30%;
        font-size: 14px;
        color: white;
      }

      .infoSpeed {
        width: 70%;

        & /deep/ .el-progress-bar {
          width: 90%;
        }
      }

      & /deep/ .cornerTopLeft {
        left: -2px;
        top: -2px;
      }

      & /deep/ .cornerTopRight {
        top: -2px;
        right: -2px;
      }

      & /deep/ .cornerBottomLeft {
        bottom: -2px;
        left: -2px;
      }

      & /deep/ .cornerBottomRight {
        bottom: -2px;
        right: -2px;
      }

      & /deep/ .corner {
        position: absolute;
        height: 25px;
        width: 25px;

        img {
          height: 100%;
          width: 100%;
        }
      }
      &.mr0{
        margin-right: 0;
      }
      &:nth-of-type(5n) {
        margin-right: 0;
      }
      /*&:nth-of-type(5), &:nth-of-type(10) {*/
      /*  margin-right: 0;*/
      /*}*/
    }
  }

  /*  复制*/
  .upload-tip {
    margin-top: 5px;
    font-size: 12px;
    color: white;
  }
  .scrollColor{

  }
  .loading{
    text-align: center;
    color: wheat;
    padding-bottom: 5px;
    font-size: 16px;
    width: 100%;
    /* margin-top: -3px; */
    /*position: relative;*/
    /*font-size: 16px;*/
    /*top: -3%;*/
  }
</style>

